package com.xaicode.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.xaicode.auth.base.BaseMpServiceImpl;
import com.xaicode.auth.constant.EnableEnum;
import com.xaicode.auth.entity.SysMenu;
import com.xaicode.auth.enums.MenuType;
import com.xaicode.auth.mapper.SysMenuMapper;
import com.xaicode.auth.security.LoginUtil;
import com.xaicode.auth.security.domain.params.SysMenuQueryParam;
import com.xaicode.auth.security.domain.query.SysMenuQueryCriteria;
import com.xaicode.auth.service.ISysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends BaseMpServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<SysMenu> list(SysMenuQueryParam param) {

        // 仅获取启用菜单
        param.setStatus(EnableEnum.ENABLE.getCode());

        SysMenuQueryCriteria criteria = new SysMenuQueryCriteria();
        criteria.setStatus(EnableEnum.ENABLE.getCode());

        // 管理员登录，返回所有菜单
        if (LoginUtil.isAdminLogin()) {
            LambdaQueryWrapper<SysMenu> lqw = Wrappers.lambdaQuery();
            lqw.eq(Objects.nonNull(param.getStatus()), SysMenu::getStatus, param.getStatus());
            lqw.like(StrUtil.isNotBlank(param.getMenuName()), SysMenu::getMenuName, param.getMenuName());
            lqw.orderByAsc(SysMenu::getParentId, SysMenu::getSortNum);
            return list(lqw);
        }

        // 查询当前用户分配的菜单
        String userId = StpUtil.getLoginIdAsString();
        return baseMapper.selectMenus(userId, param.getStatus());
    }

    @Override
    public List<SysMenu> getMenusByUserId(String userId) {
        // 管理员登录，返回所有菜单
        if (LoginUtil.isAdminLogin()) {
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<SysMenu>()
                    /* 仅查询启用菜单 */
                    .eq(SysMenu::getStatus, EnableEnum.ENABLE.getCode())
                    /* 忽略按钮 */
                    .ne(SysMenu::getMenuType, MenuType.BUTTON.getValue());
            return list(queryWrapper);
        }

        // 非管理员，加入用户id筛选数据
        return baseMapper.getMenusByUserId(userId,
                EnableEnum.ENABLE.getCode(), MenuType.BUTTON.getValue());
    }

    @Override
    public List<String> getMenuPermissionByUserId(String userId) {
        List<SysMenu> menus = baseMapper.getMenuPermissionByUserId(userId, EnableEnum.ENABLE.getCode());
        return menus.stream()
                .map(SysMenu::getPermission)
                .distinct()
                .collect(Collectors.toList());
    }


}
